import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;


public class Renderer {
	
	Map<String, Texture> textures;
	
	private void initGL(int width, int height) {
		try {
			Display.setDisplayMode(new DisplayMode(width,height));
			Display.create();
			Display.setVSyncEnabled(true);
		} catch (LWJGLException e) {
			e.printStackTrace();
			System.exit(0);
		}

		GL11.glEnable(GL11.GL_TEXTURE_2D);               
        
		GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);          
        
        	// enable alpha blending
        	GL11.glEnable(GL11.GL_BLEND);
        	GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
        
        	GL11.glViewport(0,0,width,height);
		GL11.glMatrixMode(GL11.GL_MODELVIEW);

		GL11.glMatrixMode(GL11.GL_PROJECTION);
		GL11.glLoadIdentity();
		GL11.glOrtho(0, width, height, 0, 1, -1);
		GL11.glMatrixMode(GL11.GL_MODELVIEW);
	}
	
	public void drawSprite(String path, int x, int y) {
		Texture t = textures.get(path);
		if (t == null) {
			loadTexture(path);
			t = textures.get(path);
		}
		
		Color.white.bind();
	
		t.bind(); // or GL11.glBind(texture.getTextureID());
		
		GL11.glBegin(GL11.GL_QUADS);
			GL11.glTexCoord2f(0, 0);
			GL11.glVertex2f(x,y);
			GL11.glTexCoord2f(0.7f, 0);
			GL11.glVertex2f(x+t.getImageWidth(),y);
			GL11.glTexCoord2f(0.7f, 0.6f);
			GL11.glVertex2f(x+t.getImageWidth(),y+t.getImageHeight());
			GL11.glTexCoord2f(0, 0.6f);
			GL11.glVertex2f(x,y+t.getImageHeight());
		GL11.glEnd();
			
	}
	
	private void loadTexture(String path) {
		
		try {
			// load texture from PNG file
			textures.put(path, TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(path)));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void render() {
		
		
		Display.update();
		Display.sync(100);

		if (Display.isCloseRequested()) {
			Display.destroy();
			System.exit(0);
		}
		
		GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
	}

	
	Renderer(int width, int height) {
		textures = new HashMap<String, Texture>();
		initGL(width, height);
		GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
		//loadTexture("peonlogo.png");
		
	}
	
}
